//
//  WenBaDetailController.m
//  suRead
//
//  Created by nancy  on 16/9/13.
//  Copyright © 2016年 bao. All rights reserved.
//
#import "WenBaDetailController.h"
#import "Masonry.h"
#import "MJRefresh.h"
#import "UIControl+Blocks.h"
#import "UIViewController+HUD.h"
#import "UIImageView+WebCache.h"
#import "ServiceNews.h"
#import "UIApplication+VisibleViewController.h"

#import "M_WenbaDetail.h"
#import "M_Question.h"
#import "M_News.h"
#import "AccountManager.h"
#import "UIAlertView+Blocks.h"

#import "QuestionCell.h"
#import "WenBaDetailHeader.h"
#import "ShareService.h"

#import "NewsDetailViewController.h"
#import "SendQuestionController.h"
#import "LoginViewController.h"
#import "QuestionCommentListController.h"
#import "WenBaTagListController.h"
#import "FMDBHelpers.h"

#define ScreenRectHeight [UIScreen mainScreen].applicationFrame.size.height
#define ScreenRectWidth [UIScreen mainScreen].applicationFrame.size.width

@interface WenBaDetailController ()<UITableViewDataSource,UITableViewDelegate,WenBaDetailHeaderDelegate>

@property (nonatomic,strong)M_WenbaDetail *wenbaDetail;
@property (nonatomic,strong)NSMutableArray *listQuestions;

@property (nonatomic,strong)UITableView *newsTableView;
@property (nonatomic,strong)NSURLSessionDataTask *requestHandle;
@property (nonatomic,assign)NSInteger currentPageIndex;
@property (nonatomic,strong) UIButton *zanbtn;
@property (nonatomic,strong) UIButton *buttonZan;

@end

@implementation WenBaDetailController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.navigationBarHidden = YES;
    [self setNeedsStatusBarAppearanceUpdate];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor colorWithRed:240/255.0f green:240/255.0f blue:240/255.0f alpha:1.0f];
    __weak typeof(self) weak_self = self;
    
    self.newsTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.newsTableView.separatorStyle = UITableViewCellSelectionStyleNone;
    self.newsTableView.delegate = self;
    self.newsTableView.dataSource = self;
    self.newsTableView.tableFooterView = [UIView new];
    self.newsTableView.backgroundColor=[UIColor colorWithRed:240/255.0f green:240/255.0f blue:240/255.0f alpha:1.0f];
    UIView *bottomBarView = [UIView new];
    bottomBarView.backgroundColor = [UIColor colorWithRed:251/255.0f green:251/255.0f blue:251/255.0f alpha:1.0f];
    
    [self.view addSubview:self.newsTableView];
    [self.view addSubview:bottomBarView];
    [bottomBarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(weak_self.view);
        make.height.equalTo(@44.0f);
    }];
    [self.newsTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weak_self.view).with.offset(20.0f);
        make.left.right.equalTo(weak_self.view);
        make.bottom.mas_equalTo(bottomBarView.mas_top);
    }];
    self.newsTableView.sectionFooterHeight = 0;
    self.newsTableView.contentInset = UIEdgeInsetsMake(0, 0, 10.0f, 0);
    
    [self.newsTableView registerNib:[UINib nibWithNibName:@"WenBaDetailHeader" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"WenBaDetailHeader"];
    [self.newsTableView registerNib:[UINib nibWithNibName:@"QuestionCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"QuestionCell"];
    
    UIButton *buttonBack = [UIButton buttonWithType:UIButtonTypeCustom];
    [buttonBack setImage:[UIImage imageNamed:@"button_backward"] forState:UIControlStateNormal];
    [buttonBack addActionForControlEvents:UIControlEventTouchUpInside usingBlock:^(UIControl *sender, UIEvent *event) {
        //返回
        [weak_self.navigationController popViewControllerAnimated:YES];
        [weak_self dismissViewControllerAnimated:YES completion:^{
            
        }];
    }];
    
    UIButton *buttonViewComment = [UIButton buttonWithType:UIButtonTypeCustom];
    [buttonViewComment setImage:[UIImage imageNamed:@"button_ask"] forState:UIControlStateNormal];
    [buttonViewComment addActionForControlEvents:UIControlEventTouchUpInside usingBlock:^(UIControl *sender, UIEvent *event) {
        [self toAsk];
    }];
    
    UIButton *tiwenbtn = [UIButton buttonWithType:UIButtonTypeCustom];
    tiwenbtn.titleLabel.font = [UIFont systemFontOfSize:16.0f];
    [tiwenbtn setTitleColor:[UIColor darkGrayColor]forState:UIControlStateNormal];
    [tiwenbtn setTitle:@"提问" forState:UIControlStateNormal];
    [tiwenbtn addActionForControlEvents:UIControlEventTouchUpInside usingBlock:^(UIControl *sender, UIEvent *event) {
        [self toAsk];
    }];
    
    UIButton *buttonShare = [UIButton buttonWithType:UIButtonTypeCustom];
    [buttonShare setImage:[UIImage imageNamed:@"icon_zb_share"] forState:UIControlStateNormal];
    [buttonShare addActionForControlEvents:UIControlEventTouchUpInside usingBlock:^(UIControl *sender, UIEvent *event) {
        [self toShare];
    }];
    
    UIButton *sharebtn = [UIButton buttonWithType:UIButtonTypeCustom];
    sharebtn.titleLabel.font = [UIFont systemFontOfSize:16.0f];
    [sharebtn setTitleColor:[UIColor darkGrayColor]forState:UIControlStateNormal];
    [sharebtn setTitle:@"分享" forState:UIControlStateNormal];
    [sharebtn addActionForControlEvents:UIControlEventTouchUpInside usingBlock:^(UIControl *sender, UIEvent *event) {
        [self toShare];
    }];
    
    UILabel *linelab = [UILabel new];
    linelab.backgroundColor = [UIColor colorWithRed:160/255.0f green:160/255.0f blue:160/255.0f alpha:1.0f];
    
    UILabel *linelab2 = [UILabel new];
    linelab2.backgroundColor = [UIColor colorWithRed:192/255.0f green:193/255.0f blue:194/255.0f alpha:1.0f];
    UILabel *linelab3 = [UILabel new];
    linelab3.backgroundColor = [UIColor colorWithRed:192/255.0f green:193/255.0f blue:194/255.0f alpha:1.0f];
    
    
    self.buttonZan = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.buttonZan setImage:[UIImage imageNamed:@"btn_praise"] forState:UIControlStateNormal];
    [self.buttonZan addActionForControlEvents:UIControlEventTouchUpInside usingBlock:^(UIControl *sender, UIEvent *event) {
        [weak_self doZan];
    }];
    
    self.zanbtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.zanbtn.titleLabel.font = [UIFont systemFontOfSize:16.0f];
    self.zanbtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;//设置title的字体居左
    [self.zanbtn setTitle:@"点赞" forState:UIControlStateNormal];
    [self.zanbtn setTitleColor:[UIColor darkGrayColor]forState:UIControlStateNormal];
    [self.zanbtn addActionForControlEvents:UIControlEventTouchUpInside usingBlock:^(UIControl *sender, UIEvent *event) {
        [weak_self doZan];
    }];
    
    [bottomBarView addSubview:linelab];
    [bottomBarView addSubview:linelab2];
    [bottomBarView addSubview:linelab3];
    [bottomBarView addSubview:buttonBack];
    [bottomBarView addSubview:buttonViewComment];
    [bottomBarView addSubview:tiwenbtn];
    [bottomBarView addSubview:buttonShare];
    [bottomBarView addSubview:sharebtn];
    [bottomBarView addSubview:_buttonZan];
    [bottomBarView addSubview:_zanbtn];
    
    [linelab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(bottomBarView);
        make.height.equalTo(@0.5f);
    }];
    
    [buttonBack mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(bottomBarView).with.offset(8.0f);
        make.centerY.equalTo(bottomBarView);
        make.width.equalTo(@28.0f);
        make.height.equalTo(@28.0f);
    }];
    
    
    [buttonShare mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(bottomBarView);
        make.centerY.equalTo(bottomBarView);
        make.width.equalTo(@28.0f);
        make.height.equalTo(@28.0f);
    }];
    
    [sharebtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(buttonShare.mas_right).with.offset(3.0f);
        make.centerY.equalTo(bottomBarView);
        make.width.equalTo(@35.0f);
        make.height.equalTo(@28.0f);
    }];
    
    [linelab2 mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.right.mas_equalTo(buttonShare.mas_left).with.offset(-23.0f);
        make.centerY.equalTo(bottomBarView);
        make.height.equalTo(@28.0f);
        make.width.equalTo(@0.8f);
        
    }];
    
    
    [linelab3 mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(sharebtn.mas_right).with.offset(13.0f);
        make.centerY.equalTo(bottomBarView);
        make.height.equalTo(@28.0f);
        make.width.equalTo(@0.8f);
        
    }];

    
    
    [tiwenbtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(linelab2.mas_left).with.offset(-13.0f);
        make.centerY.equalTo(bottomBarView);
        make.width.equalTo(@35.0f);
        make.height.equalTo(@28.0f);
    }];
    [buttonViewComment mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(tiwenbtn.mas_left).with.offset(-3.0f);
        make.centerY.equalTo(bottomBarView);
        make.width.equalTo(@28.0f);
        make.height.equalTo(@28.0f);
    }];

    [_buttonZan mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(linelab3.mas_right).with.offset(23.0f);
        make.centerY.equalTo(bottomBarView);
        make.width.equalTo(@28.0f);
        make.height.equalTo(@28.0f);
    }];
    [self.zanbtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(_buttonZan.mas_right).with.offset(3.0f);
        make.centerY.equalTo(bottomBarView);
        make.width.equalTo(@35.0f);
        make.height.equalTo(@28.0f);
    }];
    
    
    
    
    
    self.newsTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        //刷新数据
        [weak_self refreshData];
    }];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.1f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [weak_self.newsTableView.mj_header beginRefreshing];
    });
    
    
}

- (void)toAsk
{
    if (![AccountManager sharedAccountManager].f_isLogined) {
        [UIAlertView showWithTitle:@"提示" message:@"提问请先登录并绑定手机号" cancelButtonTitle:@"取消" otherButtonTitles:@[@"确认"] tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
            if (buttonIndex == 1)
            {
                
                
                UIStoryboard *personalCenterStoryBoard = [UIStoryboard storyboardWithName:@"PersonalCenter" bundle:[NSBundle mainBundle]];
                LoginViewController *controller = [personalCenterStoryBoard instantiateViewControllerWithIdentifier:@"LoginViewController"];
                controller.hidesBottomBarWhenPushed = YES;
                [[[UIApplication sharedApplication] visibleViewController].navigationController pushViewController:controller animated:YES];
                
            }
        }];
        return;
    }else{
        //提问界面
        if([self.wenbaDetail.f_zhuanjia_status isEqualToString:@"进行中"]){
            SendQuestionController *controller = [SendQuestionController new];
            controller.f_zhuanjia_id = self.wenbaDetail.f_zhuanjia_id;
            [self.navigationController pushViewController:controller animated:YES];
        }else{
            [self showHUDText:@"当前专家已结束服务。"];

        }
        
        
    }
}

- (void)toShare
{
    NSString *shareUrl_ = self.wenbaDetail.f_shareurl;
    if ([shareUrl_ rangeOfString:@"?"].location != NSNotFound)
    {
        shareUrl_ = [shareUrl_ stringByAppendingString:[NSString stringWithFormat:@"&uct=%@",[ServiceNews getAuthCode]]];
    }
    
    [ShareService share:self url:shareUrl_ title:self.wenbaDetail.f_title image:self.wenbaDetail.f_background_img completion:nil];
}

- (void)doZan
{
    __weak typeof(self) weak_self = self;
    if (![[FMDBHelpers sharedInstance] queryData:_wenbaDetail.f_id type:3
          ]) {
        //赞
        [ServiceNews doZanQuestion:_wenbaDetail.f_id
                              type:@"zhuanjia"
                           success:^(id responseObject, NSString *message) {
                               [[FMDBHelpers sharedInstance] insertData:_wenbaDetail.f_id andType:3];
                               [weak_self.buttonZan setImage:[UIImage imageNamed:@"btn_praised"] forState:UIControlStateNormal];
                               int intString = [_wenbaDetail.f_square intValue]+1;
                               NSString *newSquare=[NSString stringWithFormat:@"%d",intString];
                                [_zanbtn setTitle:newSquare forState:UIControlStateNormal];
                           } failure:^(NSString *message) {
                           }];
        
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = YES;
}

- (void)refreshData
{
    self.currentPageIndex = 1;
    if (self.requestHandle) {
        [self.requestHandle cancel];
        self.requestHandle = nil;
    }
    
    __weak typeof(self) weak_self = self;
    [self showHUDProgress:@""];
    [ServiceNews doFetchWenBaDetail:self.subURL success:^(id responseObject, NSString *message) {
        [weak_self.newsTableView.mj_header endRefreshing];
        weak_self.wenbaDetail = responseObject;
        [_zanbtn setTitle:weak_self.wenbaDetail.f_square forState:UIControlStateNormal];
        if ([[FMDBHelpers sharedInstance] queryData:weak_self.wenbaDetail.f_id type:3]) {
            [weak_self.buttonZan setImage:[UIImage imageNamed:@"btn_praised"] forState:UIControlStateNormal];
        } else {
            [weak_self.buttonZan setImage:[UIImage imageNamed:@"btn_praise"] forState:UIControlStateNormal];
        }
        NSArray *listQuestions_ = _wenbaDetail.f_questions;
        weak_self.listQuestions = [NSMutableArray array];
        if (listQuestions_) {
            [weak_self.listQuestions addObjectsFromArray:listQuestions_];
        }
        [weak_self.newsTableView reloadData];
        [weak_self removeHUDProgress];
    } failure:^(NSString *message) {
        [weak_self removeHUDProgress];
        [weak_self showHUDText:message];
        [weak_self.newsTableView.mj_header endRefreshing];
        
    }];
}

//- (CGFloat)tableView:(UITableView *)tableView heightForFootInSection:(NSInteger)section
//{
//    return 10.0f;
//}

#pragma mark tableViewDatasouce Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (!section) {
        return 1;
    }
    else {
        return [self.listQuestions count];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (!indexPath.section) {
        //问吧详情头部信息
        WenBaDetailHeader *cell = [tableView dequeueReusableCellWithIdentifier:@"WenBaDetailHeader"];
        cell.wenbaDetailData = _wenbaDetail;
        cell.wenBaDetailHeaderDelegate=self;
        //自定义cell的回调，获取要展开/收起的cell。刷新点击的cell
        cell.showMoreTextBlock = ^(UITableViewCell *currentCell){
            NSIndexPath *indexRow = [_newsTableView indexPathForCell:currentCell];
            [self.newsTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexRow, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
        };
        return cell;
    }
    else {
        //问题cell
        M_Question *question = [self.listQuestions objectAtIndex:indexPath.row];
        QuestionCell *cell = [tableView dequeueReusableCellWithIdentifier:@"QuestionCell"];
        question.f_zhuanjia_img=_wenbaDetail.f_zhuanjia_img;
        question.f_zhuanjia_name=_wenbaDetail.f_zhuanjia_name;
        cell.cellData=question;
        [cell setCommentlistClickCallBack:^(){
            //评论列表
            QuestionCommentListController *controller = [QuestionCommentListController new];
            controller.commentsUrl=question.f_url;
            controller.question_id=question.f_question_id;
            [self.navigationController pushViewController:controller animated:YES];
        }];
        return cell;
    }
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (!indexPath.section) {
        //问吧详情头部
        return [WenBaDetailHeader heightWithContent:_wenbaDetail];
    }
    else
    {
        
        M_Question *question_= [self.listQuestions objectAtIndex:indexPath.row];
        return [QuestionCell heightWithContent:question_];
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section) {
        M_Question *question_ = [self.listQuestions objectAtIndex:indexPath.row];
        [self jumpToQuestionComments:question_];
    }
}

- (void)jumpToQuestionComments:(M_Question *)question_
{
    //评论列表
    QuestionCommentListController *controller = [QuestionCommentListController new];
    controller.commentsUrl=question_.f_url;
    controller.question_id=question_.f_question_id;
    [self.navigationController pushViewController:controller animated:YES];
}

-(void) toWenBaCtgListPage:(NSString *) ctgUrl{
    //去问吧专题界面
    //专题
    WenBaTagListController *controller = [WenBaTagListController new];
    controller.hidesBottomBarWhenPushed = YES;
    controller.subURL =ctgUrl;
    [self.navigationController pushViewController:controller animated:YES];
}

@end
